import java.beans.DefaultPersistenceDelegate;
import java.beans.Encoder;
import java.beans.Expression;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class FileUtils
{

    public static XMLEncoder getXMLEncoder(OutputStream os)
    {
        XMLEncoder encoder = new XMLEncoder(os);
        encoder.setPersistenceDelegate(BigDecimal.class, new DefaultPersistenceDelegate()
        {
            protected Expression instantiate(Object oldInstance, Encoder out)
            {
                BigDecimal bd = (BigDecimal) oldInstance;
                return new Expression(oldInstance, oldInstance.getClass(), "new", new Object[]
                { bd.toString() });
            }

            protected boolean mutatesTo(Object oldInstance, Object newInstance)
            {
                return oldInstance.equals(newInstance);
            }
        });
        encoder.setPersistenceDelegate(HashMap.class, encoder.getPersistenceDelegate(Map.class));
        return encoder;
    }

    public static void saveObjectToXML(Object o, String fileName)
    {

        try
        {
            FileOutputStream os = new FileOutputStream(fileName);
            XMLEncoder encoder = getXMLEncoder(os);
            try
            {
                encoder.writeObject(o);
            } finally
            {
                encoder.close();
                os.close();
            }
        } catch (Throwable e)
        {
            e.printStackTrace();
        }
    }

    public static Object loadObjectFromXML(String fileName)
    {
        Object o = null;
        FileInputStream os = null;
        try
        {
            os = new FileInputStream(fileName);
            XMLDecoder decoder = new XMLDecoder(os);
            o = decoder.readObject();
            decoder.close();
        } catch (Throwable e)
        {
            e.printStackTrace();
        } finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return o;
    }

}
